import { onMounted, onUnmounted, type Ref } from 'vue'

export interface CodeRainOptions {
  letters?: string
  colors?: string[]
  fontSize?: number
  animationSpeed?: number
}

export const useCodeRain = (canvasRef: Ref<HTMLCanvasElement | null>, options?: CodeRainOptions) => {
  const {
    letters = 'CodeForce',
    colors = ['#05FF00', '#00BFFF', '#FF4500', '#FFA500', '#C202C2'],
    fontSize = 10,
    animationSpeed = 60
  } = options || {}

  let ctx: CanvasRenderingContext2D | null = null
  let drops: number[] = []
  let columns = 0
  let animationInterval: number
  const colorIndex = Math.floor(Math.random() * colors.length)

  function draw() {
    if (!ctx || !canvasRef.value) return
    
    ctx.fillStyle = 'rgba(0, 0, 0, .1)'
    ctx.fillRect(0, 0, canvasRef.value.width, canvasRef.value.height)
    ctx.fillStyle = colors[colorIndex]
    
    for (let i = 0; i < drops.length; i++) {
      const text = letters[Math.floor(Math.random() * letters.length)]
      ctx.fillText(text, i * fontSize, drops[i] * fontSize)
      drops[i]++
      if (drops[i] * fontSize > canvasRef.value!.height && Math.random() > 0.95) {
        drops[i] = 0
      }
    }
  }

  function initCanvas() {
    if (!canvasRef.value) return
    
    canvasRef.value.width = window.innerWidth
    canvasRef.value.height = window.innerHeight
    ctx = canvasRef.value.getContext('2d')
    
    columns = Math.floor(canvasRef.value.width / fontSize)
    drops = Array(columns).fill(1)
    
    if (ctx) {
      ctx.font = `${fontSize}px monospace`
    }
    
    animationInterval = setInterval(draw, animationSpeed)
  }

  function handleResize() {
    if (canvasRef.value) {
      canvasRef.value.width = window.innerWidth
      canvasRef.value.height = window.innerHeight
      columns = Math.floor(canvasRef.value.width / fontSize)
      drops = Array(columns).fill(1)
    }
  }

  onMounted(() => {
    initCanvas()
    window.addEventListener('resize', handleResize)
  })

  onUnmounted(() => {
    clearInterval(animationInterval)
    window.removeEventListener('resize', handleResize)
  })

  return {
    initCanvas,
    handleResize,
    destroy: () => {
      clearInterval(animationInterval)
      window.removeEventListener('resize', handleResize)
    }
  }
}